//
//  STOMPClientManager.m
//  NewPro
//
//  Created by RYX on 2019/2/20.
//  Copyright © 2019 何荧红. All rights reserved.
//

#import "STOMPClientManager.h"
#import "UserModel.h"
#import "HomeList.h"

@interface STOMPClientManager()<STOMPClientDelegate>

@end

@implementation STOMPClientManager

- (instancetype)init{
    
    if (self = [super init]) {
        
        NSURL *websocketUrl = [NSURL new];
        #ifdef DEBUG
        
            websocketUrl = [NSURL URLWithString:@"ws://120.27.239.20:8083/customer-service/websocket"];
        #else
        
            websocketUrl = [NSURL URLWithString:@"ws://www.forcard.store:8083/customer-service/websocket"];
        #endif
        
        self.client = [[STOMPClient alloc] initWithURL:websocketUrl webSocketHeaders:nil useHeartbeat:NO];
        self.client.delegate = self;
    }
    
    return self;
}

+ (instancetype)sharedInstance{
    
    static STOMPClientManager *sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedClient = [[STOMPClientManager alloc] init];
    });
    return sharedClient;
}


- (void)returnText:(StompReciveBlock)block{
    
    self.block = block;
}

- (void) clientContent{
    
    if (![self.client connected]) {
        
        MJWeakSelf
        [self.client connectWithLogin:@"1" passcode:@"1" completionHandler:^(STOMPFrame *_, NSError *error) {
            
            NSLog(@"当前连接状态：%d",[self.client connected]);
            
            if (error) {
                NSLog(@"%@", error);
                return;
            }
            
            UserModel *model = [HomeList sharedInstance].userModel;
            NSString *subTo = [NSString stringWithFormat:@"/topic/customer/%@-%@",model.realName,model.phoneNumber];
            [weakSelf.client subscribeTo:subTo messageHandler:^(STOMPMessage *message) {
                
                if (weakSelf.block != nil) {
                    weakSelf.block(message.body);
                }
                
            }];
        }];
    }
    
}

- (void)sendMsg:(NSString *)msg{
    
    UserModel *model = [HomeList sharedInstance].userModel;
    NSString *content = [StrTool encodeBase64:msg];
    NSString *from = [StrTool encodeBase64:[NSString stringWithFormat:@"%@-%@",model.realName,model.phoneNumber]];
    NSString *sign = [NSString stringWithFormat:@"%@-%@",model.phoneNumber,[StrTool currentTimeStr]];
    NSString *mmsg = [NSString stringWithFormat:@"{\"content\":\"%@\",\"from\":\"%@\",\"sign\":\"%@\"}",content,from,sign];
    [self.client sendTo:@"/app/v1/customer" body:mmsg];
    
}

#pragma mark - 断线重连
- (void) websocketDidDisconnect: (NSError *)error{

    [self clientContent];
}
@end
